/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-07-16     MBW       the first version
 */
#include "delay_uil.h"

 void thread_delay_until_handle(void *param)
{
    d_until_t _obj = param;

    rt_sem_release(&_obj->sem);
}
d_until_t delay_until_create(const char *name)
{
    d_until_t _obj;

    _obj = rt_malloc(sizeof(struct d_until));
    if (_obj == RT_NULL)
    {
        return RT_NULL;
    }
    rt_memset(_obj, 0, sizeof(struct d_until));
    rt_timer_init(&_obj->time, name, thread_delay_until_handle,
                    _obj, 0, RT_TIMER_FLAG_PERIODIC);
    rt_sem_init(&_obj->sem, name, 0, RT_IPC_FLAG_FIFO);
    return _obj;
}
rt_err_t delay_until_run(d_until_t obj, rt_tick_t tick)
{
    if (obj->tick != tick)
    {
        rt_timer_stop(&obj->time);
        rt_timer_control(&obj->time, RT_TIMER_CTRL_SET_TIME, &tick);
        obj->tick = tick;
        rt_timer_start(&obj->time);
    }
    return rt_sem_take(&obj->sem, RT_WAITING_FOREVER);
}
void delay_until_delete(d_until_t obj)
{
    rt_timer_detach(&obj->time);
    rt_sem_detach(&obj->sem);
}
